<!-- 红包商城 运费模板管理 --> 
<template>
  <div class="table">
    <el-tabs v-model="activeName" @tab-click="handleChangeTabs">
      <el-tab-pane label="运费模版列表" name="one">
        <div class="container">
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>
                <el-icon>
                  <Search />
                </el-icon> 查询条件：
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-row :gutter="10">
            <el-col :xl="6" :lg="8" :md="12" :sm="24" style="margin-bottom:10px">
              <el-input v-model.trim="searchCondition.deliver_name" placeholder="模板名称" clearable></el-input>
            </el-col>
            <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
              <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
              <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>查询结果：</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="handle-box">
            <el-button type="primary" :icon="Plus" class="mr10" :disabled="disabledbtn" @click="setActiveName('two')">新增
            </el-button>
            <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete('deleteMallDeliverInfo')">
              <template #reference>
                <el-button type="danger" :icon="Delete" class="mr10" :disabled="disabledbtn">批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
          <el-table :data="tableState.tableList.slice((pageNumber - 1) * pageSize, pageNumber * pageSize)" border
            class="table" ref="multipleTableRef" v-loading="tableLoading" :reserve-selection="true"
            @row-dblclick="rowDblclick">
            <el-table-column type="index" align="center"> </el-table-column>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="deliver_name" label="模板名称" align="center">
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" text :icon="View"
                  @click="handleViewEdit(scope.row, 'view', '查看')">
                  查看
                </el-button>
                <el-button type="primary" size="small" text :icon="Edit" v-permission="'edit'"
                  @click="handleViewEdit(scope.row, 'edit', '编辑')">
                  编辑
                </el-button>
                <div class="mlr10 display-inline-block" v-permission="'delete'">
                  <el-popconfirm placement="top" width="160" title="你确定要删除吗?"
                    @confirm="deleteInfo('deleteMallDeliverInfo', [id])">
                    <template #reference>
                      <el-button text :icon="Delete" size="small" class="red" @click="id = scope.row.id">删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination background @update:current-page="handleCurrentChange" @update:page-size="handleSizeChange"
              layout="total, sizes, prev, pager, next, jumper" :page-size="pageSize" :current-page="pageNumber"
              :page-sizes="pageSizes" :total="total" :hide-on-single-page="false">
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="运费模版详情" name="two">
        <!-- <span slot="label"><i class="el-icon-tickets"></i> 运费模版详情</span> -->
        <div class="container" v-loading="formLoading">
          <el-form ref="freighTemplateFormRef" :model="freighTemplateForm" :rules="rules" label-width="150px">
            <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-form-item label="模板名称：" prop="deliver_name">
                  <el-input v-model.trim.number="freighTemplateForm.deliver_name" placeholder="请输入运费模板">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="left"><span class="title-left-color">配送区域及运费 </span></el-divider>
            <div class="handle-box">
              <el-button type="primary" :icon="Plus" class="mr10" :disabled="disabledbtn"
                @click="handleAddDeliverData">新增
              </el-button>
            </div>
            <el-table :data="freighTemplateForm.regionArray" border class="table" ref="freighTemplateFormRegionArray"
              :reserve-selection="true">
              <el-table-column type="index" align="center"> </el-table-column>
              <el-table-column prop="deliver_name" label="可配送区域" align="center">
                <template #default="scope">
                  <div class="">
                    <div>{{ scope.row.provinceName }}</div>
                    <div class="">
                      <el-button type="primary" text :icon="Plus" v-if="scope.row.provinceName === ''"
                        @click="handleAddProvince(scope.$index, scope.row)">添加</el-button>
                      <el-button type="primary" text :icon="Edit" v-else
                        @click="handleEditProvince(scope.$index, scope.row)">编辑</el-button>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="first_unit" label="首件（个）" align="center">
                <template #default="scope">
                  <div class="">
                    <el-input v-model.number.trim="scope.row.first_unit" placeholder="请输入内容"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="first_price" label="首费（元）" align="center">
                <template #default="scope">
                  <div class="">
                    <el-input v-model.trim="scope.row.first_price" placeholder="请输入内容"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="renew_unit" label="续件（个）" align="center">
                <template #default="scope">
                  <div class="">
                    <el-input v-model.number.trim="scope.row.renew_unit" placeholder="请输入内容"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="renew_price" label="续费（元）" align="center">
                <template #default="scope">
                  <div class="">
                    <el-input v-model.trim="scope.row.renew_price" placeholder="请输入内容"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" align="center">
                <template #default="scope">
                  <div class="mlr10 display-inline-block">
                    <el-popconfirm placement="top" width="160" title="你确定要删除吗?"
                      @confirm="deleteAegionArrayRow(scope.$index, scope.row)">
                      <template #reference>
                        <el-button text :icon="Delete" size="small" class="red" @click="id = scope.row.id">删除
                        </el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
          <div class="footer-center">
            <el-button @click="cancelSubmit">返 回</el-button>
            <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn"
              @click="submitForm('commonMallDeliverInfo', getTableInfo, handleValidAssignment)">确
              定
            </el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 新增编辑查看弹出框 -->
    <el-dialog title="配送区域" v-model="editVisible" width="50%" draggable :close-on-click-modal="false"
      @closed="closedFormDialog">
      <el-form label-width="150px">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="选择可配送区域：" prop="name">
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                @change="handleCheckAllChange">全选</el-checkbox>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group v-model="state.checkedProvinces" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="item in state.provinceSelectList" :label="item.id" :key="item.id">{{ item.name
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelSelectProvince">取 消</el-button>
          <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitSelectProvince">确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { View, Delete, Edit, Search, Plus, Refresh } from '@element-plus/icons-vue';
import { api as Request } from '@/utils/api';
import { useTable } from '@/hooks/useTable.js';
import { useTabsForm } from '@/hooks/useTabsForm.js';
import useRules from '@/hooks/useRules.js';

const disabledbtn = ref(false);/*  按钮可用与不可用 */
const formLoading = ref(false);/*  对话框中数据提交加载 */
const editVisible = ref(false); /* 新增编辑显示隐藏 */
const checkAll = ref(false);/* 是否全选  */
const isIndeterminate = ref(false);/*   */
const id = ref(-1);/* 删除时所需的编号 删除时的id  */
const index = ref(-1);/* 选中可配送区域及运费数组中的第几项  index */

let { total, pageNumber, pageSize, pageSizes, multipleTableRef, tableLoading, tableState, searchCondition,
  handleCurrentChange, handleSizeChange, getTableInfo, searchInfo, resetSearch, batchDelete, deleteInfo, rowDblclick } =
  useTable({
    deliver_name: ''
  }, 'getMallDeliverInfo', disabledbtn, 'FRONT_END');
let { formRef: freighTemplateFormRef, formData: freighTemplateForm, methodType, isDisabledbtn,
  activeName, setActiveName, handleChangeTabs, submitForm, handleClearData: cancelSubmit } = useTabsForm({
    id: '',
    deliver_name: '',
    regionArray: [
      // {
      //   id: -1,
      //   first_price: 0,
      //   first_unit: 0,
      //   regions: [0],
      //   renew_price: 0,
      //   renew_unit: 0
      // }
    ]
  }, disabledbtn, handleCustomOperation, formLoading);
const state = reactive({
  provinceList: [],
  provinceSelectList: [],
  checkedProvinces: []
});

const rules = useRules('freighTemplateRules');/* 校验规则 */

/* 获取省 地址信息 */
const getRegionInfo = (params) => {
  Request.getRegionInfo({})
    .then((res) => {
      state.provinceList = JSON.parse(JSON.stringify(res.result));
      state.provinceSelectList = JSON.parse(JSON.stringify(res.result));
    })
    .catch((res) => { });
}
/* 获取运费模板详情信息 */
const getMallDeliverByIdInfo = (id) => {
  formLoading.value = true;
  Request.getMallDeliverByIdInfo({ id })
    .then((res) => {
      freighTemplateForm.id = res.result.id;
      freighTemplateForm.deliver_name = res.result.deliver_name;
      freighTemplateForm.regionArray = JSON.parse(JSON.stringify(res.result.regionArray));
      /* 删除已经选过的省 */
      let idArray = res.result.regionArray.map((item) =>
        item.regions.map((arr) => arr)
      );
      let array = [];
      idArray.forEach((item) => {
        array = [...array, ...item];
      });
      state.provinceSelectList = state.provinceSelectList.filter(
        (item) => array.lastIndexOf(item.id) < 0
      );
      handleSelectProvinceFormet();
    })
    .catch((res) => { }).finally(() => { formLoading.value = false; });
}

/* 点击编辑按钮 */
const handleViewEdit = (row, code, name) => {
  if ('view' === code) {
    isDisabledbtn.value = true;
  } else if ('edit' === code) {
    methodType.value = 'PUT';
  }
  /* 商品详情标签页显示 */
  activeName.value = 'two';
  getMallDeliverByIdInfo(row.id);
}

/* 新增 可配送区域及运费地址 */
const handleAddDeliverData = () => {
  /* 判断是否所有地区都有了 */
  let num = 0;
  for (let i = 0; i < freighTemplateForm.regionArray.length; i++) {
    num += freighTemplateForm.regionArray[i].regions.length;
  }
  if (num === state.provinceList.length) {
    ElMessage.warning('你已经选择了所有区域,无需再新增了');
    return;
  }
  /* 添加新的配送区域及运费记录 */
  let regionObj = {
    id: -1,
    first_price: 0,
    first_unit: 0,
    provinceName: '',
    regions: [],
    renew_price: 0,
    renew_unit: 0
  };
  freighTemplateForm.regionArray.push(regionObj);
}

/* 新增地址 */
const handleAddProvince = (_index, row) => {
  index.value = _index;
  editVisible.value = true;
  /* 修改可选择的省份 */
  /* 删除已经选过的省 ，自己除外 */
  let idArray = freighTemplateForm.regionArray.map((item) =>
    item.regions.map((arr) => arr)
  );
  let array = [];
  idArray.forEach((item) => {
    array = [...array, ...item];
  });
  state.provinceSelectList = state.provinceList.filter(
    (item) => array.lastIndexOf(item.id) < 0
  );
}
/* 编辑地址 */
const handleEditProvince = (_index, row) => {
  index.value = _index;
  editVisible.value = true;
  /* 修改可选择的省份 */
  /* 删除已经选过的省 ，自己除外 */
  let idArray = freighTemplateForm.regionArray.map((item) =>
    item.regions.map((arr) => arr)
  );
  let array = [];
  for (let i = 0; i < idArray.length; i++) {
    if (i !== _index) {
      array = [...array, ...idArray[i]];
    }
  }
  state.provinceSelectList = state.provinceList.filter(
    (item) => array.lastIndexOf(item.id) < 0
  );
  console.log(state.provinceSelectList);
  /* 获取已经选中的省 */

  state.checkedProvinces = row.regions;

  /* 修改全选与部分选 的样式 */
  // checkAll =
  //   checkedProvinces.length === provinceSelectList.length;
  // isIndeterminate =
  //   checkedProvinces.length > 0 &&
  //   checkedProvinces.length < provinceSelectList.length;
  /* 修改全选与部分选 的样式 */
  handleCheckAll(
    state.checkedProvinces.length,
    state.provinceSelectList.length
  );
}
/* 全选 */
const handleCheckAllChange = (val) => {
  state.checkedProvinces = val
    ? state.provinceSelectList.map((item) => item.id)
    : [];
  isIndeterminate.value = false;
}
/* 点击选择省 */
const handleCheckedCitiesChange = (value) => {
  let checkedCount = value.length;
  /* 修改全选与部分选 的样式 */
  // this.checkAll = checkedCount === this.provinceSelectList.length;
  // this.isIndeterminate =
  //   checkedCount > 0 && checkedCount < this.provinceSelectList.length;
  handleCheckAll(checkedCount, state.provinceSelectList.length);
}
/* 修改全选与部分选 的样式 */
const handleCheckAll = (checkedCount, selectListLength) => {
  checkAll.value = checkedCount === selectListLength;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < selectListLength;
}
/* 取消选择省 */
const cancelSelectProvince = () => {
  editVisible.value = false;
}
/* 确定选择省 */
const submitSelectProvince = () => {
  /* 校验是否选择数据 */
  if (state.checkedProvinces.length === 0) {
    ElMessage.warning('请至少选择一个配送区域');
    return;
  }
  /* concat会返回一个新的数组 */
  freighTemplateForm.regionArray[index.value].regions = JSON.parse(JSON.stringify(state.checkedProvinces));
  handleSelectProvinceFormet();
  /* 初始化 */
  cancelSelectProvince();
}
/* 获取选中的省 格式化 */
const handleSelectProvinceFormet = () => {
  freighTemplateForm.regionArray =
    freighTemplateForm.regionArray.filter((item) => {
      let provinceNameArray = [];
      for (let i = 0; i < item.regions.length; i++) {
        if (item.regions.length === state.provinceList.length) {
          provinceNameArray.push('全国');
          break;
        }
        for (let j = 0; j < state.provinceList.length; j++) {
          if (state.provinceList[j].id === item.regions[i]) {
            provinceNameArray.push(state.provinceList[j].name);
            break;
          }
        }
      }
      item.provinceName = provinceNameArray.join(',');
      return item;
    });
}
/* 删除可配送区域及运费地址*/
const deleteAegionArrayRow = (index, row) => {
  freighTemplateForm.regionArray.splice(index, 1);
}

/* 关闭新增编辑查看 弹出框事件 */
const closedFormDialog = () => {
  checkAll.value = false;
  state.checkedProvinces = [];
  isIndeterminate.value = false;
  index.value = -1;
}
/* 保存校验数据 */
const handleValidate = () => {
  if (freighTemplateForm.regionArray.length === 0) {
    ElMessage.warning('请新增配送区域及运费信息');
    return false;
  }
  let num = 0;
  for (let i = 0; i < freighTemplateForm.regionArray.length; i++) {
    num += freighTemplateForm.regionArray[i].regions.length;
  }
  if (num !== state.provinceList.length) {
    ElMessage.warning('还有未添加的省份，请添加');
    return false;
  }
  return true;
}
/* 删除没有存地址的数据 */
const handleNullAddress = () => {
  let i = freighTemplateForm.regionArray.length;
  while (i--) {
    if (freighTemplateForm.regionArray[i].regions.length === 0)
      freighTemplateForm.regionArray.splice(i, 1);
  }
}

/* 关闭切换标签页以后的自定义操作 */
function handleCustomOperation () {
  freighTemplateForm.id = '';
  freighTemplateForm.regionArray = [];
}

/* 保存与编辑 前的自定义校验或赋值操作 */
const handleValidAssignment = () => {
  if (!handleValidate()) return false;
  /* 删除没有存地址的数据 */
  handleNullAddress();
}

/* 获取表单数据 */
getTableInfo();

/* 获取省 地址信息 */
getRegionInfo();
</script>

<style scoped>
/* layout-布局 */
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.textAlignCenter {
  text-align: center;
}

/* 修改select的盒模型 */
.el-select {
  display: block;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 修改该属性值  查询条件，查询结果得样式 */
.el-breadcrumb {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

/* 分割线字前的蓝色 start*/
.title-left-color {
  color: #666;
  font-size: 16px;
  font-weight: 550;
}

.title-left-color::before {
  content: '';
  position: absolute;
  width: 4px;
  height: 15px;
  background: #00aeff;
  top: 3px;
  left: 10px;
}

/* end */
</style>
